
/**
 * Date:2019年5月31日下午3:18:44
 * Copyright (c) 2019, www.bwbroad.com All Rights Reserved.
 *
*/

package com.xue.im.common.coder;

import java.io.IOException;

import org.jboss.marshalling.Marshaller;
import org.jboss.marshalling.MarshallerFactory;
import org.jboss.marshalling.Marshalling;
import org.jboss.marshalling.MarshallingConfiguration;
import org.jboss.marshalling.Unmarshaller;

import io.netty.handler.codec.marshalling.DefaultMarshallerProvider;
import io.netty.handler.codec.marshalling.DefaultUnmarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallerProvider;
import io.netty.handler.codec.marshalling.MarshallingDecoder;
import io.netty.handler.codec.marshalling.MarshallingEncoder;
import io.netty.handler.codec.marshalling.UnmarshallerProvider;

/**
 * Description: 编码解码工具类 <br/>
 * Date: 2019年5月31日 下午3:18:44 <br/>
 * 
 * @author xuejianxin
 */
public class MarshallingCodeCFactory {
	/**
	 * 创建Jboss Marshalling解码器MarshallingDecoder
	 * 
	 * @return MarshallingDecoder
	 */
	public static MarshallingDecoder buildMarshallingDecoder() {
		// 首先通过Marshalling工具类的精通方法获取Marshalling实例对象 参数serial标识创建的是java序列化工厂对象。
		final MarshallerFactory marshallerFactory = marshallerFactory();
		// 根据marshallerFactory和configuration创建provider
		UnmarshallerProvider provider = new DefaultUnmarshallerProvider(marshallerFactory, getConfig());
		// 构建Netty的MarshallingDecoder对象，俩个参数分别为provider和单个消息序列化后的最大长度
		MarshallingDecoder decoder = new MarshallingDecoder(provider, 1024 * 1024 * 1);
		return decoder;
	}

	/**
	 * 创建Jboss Marshalling编码器MarshallingEncoder
	 * 
	 * @return MarshallingEncoder
	 */
	public static MarshallingEncoder buildMarshallingEncoder() {
		final MarshallerFactory marshallerFactory = marshallerFactory();
		MarshallerProvider provider = new DefaultMarshallerProvider(marshallerFactory, getConfig());
		// 构建Netty的MarshallingEncoder对象，MarshallingEncoder用于实现序列化接口的POJO对象序列化为二进制数组
		MarshallingEncoder encoder = new MarshallingEncoder(provider);
		return encoder;
	}

	private static MarshallerFactory marshallerFactory() {
		return Marshalling.getProvidedMarshallerFactory("serial");
	}

	private static MarshallingConfiguration getConfig() {
		final MarshallingConfiguration configuration = new MarshallingConfiguration();
		configuration.setVersion(5);
		return configuration;
	}

	public static Marshaller buildMarshalling() throws IOException {
		return marshallerFactory().createMarshaller(getConfig());
	}

	public static Unmarshaller buildUnmarshaller() throws IOException {
		return marshallerFactory().createUnmarshaller(getConfig());
	}

}
